import 'dart:convert';
import 'dart:io';

import 'package:emphasize_word/components/occu.dart';
import 'package:emphasize_word/content.dart';
import 'package:emphasize_word/provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin {
  var _index = 1;
  var unSelectButtonStyle = ButtonStyle(
    textStyle:
        MaterialStateProperty.all(TextStyle(fontWeight: FontWeight.bold)),
    foregroundColor: MaterialStateProperty.all(Color.fromRGBO(52, 121, 245, 1)),
    overlayColor: MaterialStateProperty.all(Color.fromRGBO(52, 121, 245, 0.1)),
  );
  var selectButtonStyle = ButtonStyle(
    textStyle:
        MaterialStateProperty.all(TextStyle(fontWeight: FontWeight.bold)),
    backgroundColor:
        MaterialStateProperty.all(Color.fromRGBO(52, 121, 245, 0.1)),
    foregroundColor: MaterialStateProperty.all(Color.fromRGBO(52, 121, 245, 1)),
    overlayColor: MaterialStateProperty.all(Color.fromRGBO(52, 121, 245, 0)),
  );
  @override
  Widget build(BuildContext context) {
    DisplayEnglish provider = Provider.of<DisplayEnglish>(context);
    ListSave provider_list = Provider.of<ListSave>(context);

    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.white,
        child: Icon(
          Icons.arrow_upward,
          color: Color.fromRGBO(52, 121, 245, 1),
        ),
        onPressed: () {
          provider_list.listViewController.animateTo(
            .0,
            duration: Duration(milliseconds: 300),
            curve: Curves.bounceInOut,
          );
        },
      ),
      backgroundColor: Color(0xFFF3F3F3),
      body: Content(),
      drawer: Drawer(
        child: DrawerCont(),
      ),
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Row(
          children: [
            Row(
              children: [
                TextButton(
                  onPressed: () {
                    provider.switchDis(0);
                  },
                  child: Text("双语"),
                  style: provider.display == 0
                      ? selectButtonStyle
                      : unSelectButtonStyle,
                ),
                TextButton(
                  onPressed: () {
                    provider.switchDis(1);
                  },
                  child: Text("仅英文"),
                  style: provider.display == 1
                      ? selectButtonStyle
                      : unSelectButtonStyle,
                ),
              ],
            ),
          ],
        ),
        leading: Builder(
          builder: (BuildContext context) {
            return IconButton(
              onPressed: () {
                Scaffold.of(context).openDrawer();
              },
              icon: Icon(
                Icons.settings,
                color: Color.fromRGBO(52, 121, 245, 1),
              ),
            );
          },
        ),
        actions: [
          IconButton(
            onPressed: () {
              provider_list.changeSort(1 - provider_list.sort);
            },
            icon: Icon(
              Icons.sort,
              color: Color.fromRGBO(52, 121, 245, 1),
            ),
          )
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class DrawerCont extends StatefulWidget {
  const DrawerCont({Key? key}) : super(key: key);

  @override
  _DrawerContState createState() => _DrawerContState();
}

class _DrawerContState extends State<DrawerCont> {
  List<Widget> drawerWidget = [];
  indexof(List arr, int ele) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == ele) {
        return i;
      }
    }
    return -1;
  }

  List<Widget> _buildLittleTip(List done, List schedule) {
    List<Widget> tmp = [];
    for (var i = 0; i < schedule.length; i++) {
      tmp.add(
        Container(
          width: 30,
          height: 30,
          decoration: BoxDecoration(
            color: indexof(done, schedule[i]) > -1
                ? Colors.white
                : Color.fromRGBO(255, 255, 255, 0.15),
            borderRadius: BorderRadius.circular(100.0),
          ),
          child: Center(
            child: Text(
              schedule[i].toString(),
              style: TextStyle(
                color: indexof(done, schedule[i]) > -1
                    ? Color.fromRGBO(52, 121, 245, 1)
                    : Colors.white,
              ),
            ),
          ),
        ),
      );
    }

    return tmp;
  }

  List schedule_backup = [];
  List done_backup = [];

  Future<List<Widget>> _buildLists(ListSave provider) async {
    var schedule = Schedule().getSchedule();
    var done = await Done().getDone(context);
    schedule_backup = schedule;
    done_backup = done;
    List<Widget> tmp_widget = [];
    for (var i = 0; i < schedule.length; i++) {
      tmp_widget.add(
        GestureDetector(
          onTap: () async {
            await provider.changeTotalIndex(i, context);
            Navigator.pop(context);
          },
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "Day${i + 1}",
                    style: TextStyle(
                        color: provider.total_day_index == i
                            ? Colors.white
                            : Color.fromRGBO(
                                255,
                                255,
                                255,
                                0.3,
                              )),
                  ),
                  Expanded(
                    child: Container(
                      height: 24,
                      child: Text(""),
                    ),
                  ),
                  Icon(
                    Icons.arrow_right,
                    color: provider.total_day_index == i
                        ? Colors.white
                        : Color.fromRGBO(
                            255,
                            255,
                            255,
                            0.3,
                          ),
                  ),
                ],
              ),
              Occu(height: 7.0),
              Wrap(
                spacing: 10.0,
                runSpacing: 10.0,
                crossAxisAlignment: WrapCrossAlignment.start,
                children: _buildLittleTip(done[i], schedule[i]),
              ),
              Occu(height: 20.0),
            ],
          ),
        ),
      );
    }
    drawerWidget = tmp_widget;
    return tmp_widget;
  }

  _getTotalProgress() {
    print("${done_backup.length}${schedule_backup.length}");
    if (done_backup.length != 0) {
      int done_num = 0;
      int total_num = 0;
      done_backup.forEach((element) {
        done_num += int.parse(element.length.toString());
      });
      schedule_backup.forEach((element) {
        total_num += int.parse(element.length.toString());
      });
      return (done_num / total_num * 100).toStringAsFixed(2);
    }
  }

  @override
  Widget build(BuildContext context) {
    ListSave provider = Provider.of<ListSave>(context);
    return Container(
      child: FutureBuilder(
        future: _buildLists(provider),
        builder: (context, snapshot) {
          return ListView(
            controller: provider.listViewController,
            physics: BouncingScrollPhysics(),
            children: [
              Padding(
                padding: EdgeInsets.all(15.0),
                child: Text(
                  "Hello",
                  style: TextStyle(
                    fontSize: 30.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(
                  left: 15.0,
                  right: 15.0,
                  bottom: 5.0,
                ),
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(15.0),
                    color: Color.fromRGBO(52, 121, 245, 1),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Column(
                      children: drawerWidget,
                    ),
                  ),
                ),
              ),
              backup(),
              getBackUp(),
              Padding(
                padding: const EdgeInsets.only(left: 15.0, bottom: 15.0),
                child: Container(
                  child: Text(
                    "总进度 ${_getTotalProgress()}%",
                    style: TextStyle(color: Colors.grey[400]),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class getBackUp extends StatelessWidget {
  const getBackUp({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ListSave provider = Provider.of<ListSave>(context);
    return Padding(
      padding: const EdgeInsets.only(
        left: 14.0,
        right: 14.0,
        top: 8.0,
        bottom: 8.0,
      ),
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.white),
          overlayColor: MaterialStateProperty.all(Colors.white),
          shadowColor: MaterialStateProperty.all(Colors.transparent),
          foregroundColor:
              MaterialStateProperty.all(Color.fromRGBO(52, 121, 245, 1)),
        ),
        onPressed: () async {
          ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
          Directory tempDir = await getTemporaryDirectory();
          final file_similar = File('${tempDir.path}/similar.json');
          final file_done = File('${tempDir.path}/done.json');
          if (data != null) {
            String tmp_data = data.text as String;
            if (jsonDecode(tmp_data)["similar"] != null &&
                jsonDecode(tmp_data)["done"] != null) {
              await file_similar
                  .writeAsString(jsonDecode(tmp_data)["similar"].toString());
              await file_done
                  .writeAsString(jsonDecode(tmp_data)["done"].toString());
            }
            Navigator.pop(context);
          }
        },
        child: Text("恢复进度"),
      ),
    );
  }
}

class backup extends StatelessWidget {
  const backup({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(
        left: 14.0,
        right: 14.0,
        top: 8.0,
        bottom: 8.0,
      ),
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.white),
          overlayColor: MaterialStateProperty.all(Colors.white),
          shadowColor: MaterialStateProperty.all(Colors.transparent),
          foregroundColor:
              MaterialStateProperty.all(Color.fromRGBO(52, 121, 245, 1)),
        ),
        onPressed: () async {
          Directory tempDir = await getTemporaryDirectory();
          final file_similar = File('${tempDir.path}/similar.json');
          final file_done = File('${tempDir.path}/done.json');
          var data1 = await file_similar.readAsString();
          var data2 = await file_done.readAsString();
          Clipboard.setData(ClipboardData(
            text: jsonEncode({
              "similar": data1,
              "done": data2,
            }),
          ));
        },
        child: Text("备份进度到剪切板"),
      ),
    );
  }
}
